package cn.school.demo.ui.answer

import android.annotation.SuppressLint
import androidx.lifecycle.ViewModelProvider
import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.databinding.DataBindingUtil
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import cn.school.demo.MyApplication
import cn.school.demo.R
import cn.school.demo.databinding.FragmentRankingBinding
import cn.school.demo.pojo.Rank
import com.ajguan.library.EasyRefreshLayout
import com.ajguan.library.LoadModel
import com.blankj.utilcode.util.LogUtils

class RankingFragment : Fragment() {

    private lateinit var viewModel: RankingViewModel
    private lateinit var binding: FragmentRankingBinding

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        viewModel = ViewModelProvider(this).get(RankingViewModel::class.java)
        binding = DataBindingUtil.inflate(inflater, R.layout.fragment_ranking, container, false)
        binding.lifecycleOwner = viewLifecycleOwner
        binding.vw = this
        init()
        return binding.root
    }

    @SuppressLint("NotifyDataSetChanged", "SetTextI18n")
    fun init() {
        viewModel.getRanking().observe(viewLifecycleOwner) {
            LogUtils.d(it.toString())
            viewModel.updateRankList(it)
            binding.rankingFragmentRecyclerView.apply {
                adapter?.notifyDataSetChanged() ?: let {
                    layoutManager = LinearLayoutManager(requireContext())
                    adapter = RankingAdapter(viewModel.rankList)
                }
            }
            var rankNum = 1
            viewModel.rankList.forEach { rank ->
                if (rank.headPortrait == MyApplication.user!!.headPortrait && rank.nickname == MyApplication.user!!.nickname) {
                    binding.apply {
                        rankingFragmentPointTextView.text = "${rank.score}分"
                        rankingFragmentNameTextView.text = rank.nickname
                        rankingFragmentRankingTextView.text = "我的排名：第${rankNum}名"
                        MyApplication.setCircleGlideByUrlString(
                            requireContext(),
                            rank.headPortrait,
                            rankingFragmentImageView
                        )
                    }
                }
                rankNum++
            }
        }
        binding.rankingFragmentEasyRefreshLayout.apply {
            loadMoreModel = LoadModel.NONE
            addEasyEvent(object :
                EasyRefreshLayout.EasyEvent {
                override fun onRefreshing() {
                    viewModel.getRanking().observe(viewLifecycleOwner) {
                        LogUtils.d(it.toString())
                        viewModel.updateRankList(it)
                        binding.rankingFragmentRecyclerView.apply {
                            adapter?.notifyDataSetChanged() ?: let {
                                layoutManager = LinearLayoutManager(requireContext())
                                adapter = RankingAdapter(viewModel.rankList)
                            }
                        }
                        var rankNum = 1
                        viewModel.rankList.forEach { rank ->
                            if (rank.headPortrait == MyApplication.user!!.headPortrait && rank.nickname == MyApplication.user!!.nickname) {
                                binding.apply {
                                    rankingFragmentPointTextView.text = "${rank.score}分"
                                    rankingFragmentNameTextView.text = rank.nickname
                                    rankingFragmentRankingTextView.text = "我的排名：第${rankNum}名"
                                    MyApplication.setCircleGlideByUrlString(
                                        requireContext(),
                                        rank.headPortrait,
                                        rankingFragmentImageView
                                    )
                                }
                            }
                            rankNum++
                        }
                        binding.rankingFragmentEasyRefreshLayout.refreshComplete()
                    }
                }

                override fun onLoadMore() {
                    //No Things
                }

            })
        }
    }

    fun gotoBack() {
        MyApplication.goto(
            R.id.action_Ranking_to_Article,
            findNavController(),
            parentFragmentManager
        )
    }

    private inner class RankingHolder(view: View) : RecyclerView.ViewHolder(view) {
        private lateinit var rank: Rank
        private val numberTextView =
            itemView.findViewById<TextView>(R.id.list_item_point_ranking_number)
        private val nameTextView =
            itemView.findViewById<TextView>(R.id.list_item_point_ranking_name)
        private val pointTextView =
            itemView.findViewById<TextView>(R.id.list_item_point_ranking_point)
        private val image =
            itemView.findViewById<ImageView>(R.id.list_item_point_ranking_image_view)

        @SuppressLint("NewApi", "SetTextI18n")
        fun bind(rank: Rank, position: Int) {
            this.rank = rank
            when (position) {
                0 -> numberTextView.setTextColor(resources.getColorStateList(R.color.red, null))
                1 -> numberTextView.setTextColor(resources.getColorStateList(R.color.orange, null))
                2 -> numberTextView.setTextColor(
                    resources.getColorStateList(
                        R.color.purple_700,
                        null
                    )
                )
                else -> numberTextView.setTextColor(
                    resources.getColorStateList(
                        R.color.black,
                        null
                    )
                )
            }
            numberTextView.text = (position + 1).toString()
            nameTextView.text = this.rank.nickname
            pointTextView.text = "${this.rank.score}分"
            MyApplication.setCircleGlideByUrlString(requireContext(), this.rank.headPortrait, image)
        }
    }

    private inner class RankingAdapter(var rankList: MutableList<Rank>) :
        RecyclerView.Adapter<RankingHolder>() {

        override fun onCreateViewHolder(
            parent: ViewGroup,
            viewType: Int
        ): RankingHolder {
            return RankingHolder(
                layoutInflater.inflate(
                    R.layout.list_item_point_ranking,
                    parent,
                    false
                )
            )
        }

        override fun onBindViewHolder(holder: RankingHolder, position: Int) {
            val rank = rankList[position]
            holder.bind(rank, position)
        }

        override fun getItemCount() = rankList.size

    }
}